#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <termios.h>
#include <jni.h>
#include <android/log.h>
#include <stdlib.h>

#define READ_COUNT 256
#define LOG_TAG "Android Serial"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)



char buf[1024];
struct termios newtio;

JNIEXPORT jint JNICALL Java_com_port_serial_SerialComm_openserial(JNIEnv *env, jobject obj, jstring strDevPath, jstring strBaud, jint vtime, jint vmin)

{
	LOGI("oepnPORT()");
	const char *devPath = (*env)->GetStringUTFChars(env, strDevPath, JNI_FALSE);
	const char *baud = (*env)->GetStringUTFChars(env, strBaud, JNI_FALSE);

//	tcflag_t baudrate = (tcflag_t) atoi(baud);
	int fd = -1;
	if ( (fd = open(devPath, O_RDONLY)) > 0)
		LOGI("open success");
	else
		LOGI("open fail");

		
	memset(&newtio, 0x00, sizeof(newtio));
	cfsetispeed(&newtio, B57600);
//	newtio.c_cflag = baudrate;
	newtio.c_cflag |= CS8;
	newtio.c_cflag |= CLOCAL;
	newtio.c_cflag |= CREAD;
	newtio.c_iflag = 0;
	newtio.c_oflag = 0;
	newtio.c_lflag = 0;
	newtio.c_cc[vtime] = 1;
	newtio.c_cc[vmin] = 1;

	tcflush(fd, TCIFLUSH);
	tcsetattr(fd, TCSANOW, &newtio);

	LOGI("port finally open success");

	return fd;
}

		
JNIEXPORT jint JNICALL Java_com_port_serial_SerialComm_closeserial(JNIEnv *env, jobject obj, jint fd)
{
	LOGI("closePORT()");
	if (fd);
	close(fd);
}

JNIEXPORT jint JNICALL Java_com_port_serial_SerialComm_readserial(JNIEnv *env, jobject obj, jint fd, jstring arr, jint length)
{
	int read_count = 0;
	char dumpString[1024];

	memset(buf, 0x00, sizeof(buf));

	if (fd == -1)
		goto out;
	read_count = read(fd, buf, length);
	LOGI("count %d", read_count);
	LOGI("%s", buf);

	
	strcpy(dumpString, buf);
	arr = (*env)->NewStringUTF(env, buf);
	dumpString[read_count] = 0;
	

	LOGI("dump success");
	
out:
	return read_count;

}
